package com.hz.erp.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hz.erp.constant.RetResponse;
import com.hz.erp.constant.RetResult;
import com.hz.erp.constant.TemperatureType;
import com.hz.erp.dao.TemperatureInfoMapper;
import com.hz.erp.dao.UserMapper;
import com.hz.erp.entity.page.PageResult;
import com.hz.erp.entity.vo.TemInfoParameterVo;
import com.hz.erp.entity.vo.TemperatureInfoVo;
import com.hz.erp.entity.vo.UserVo;
import com.hz.erp.enums.commons.DeleteFlagEnum;
import com.hz.erp.enums.commons.ManagementFlagEnum;
import com.hz.erp.enums.commons.RegistrationWayEnum;
import com.hz.erp.enums.temperature.TemperatureEnum;
import com.hz.erp.service.TemInfoService;
import com.hz.erp.utils.DateUtil;
import com.hz.erp.utils.MathUtils;
import com.hz.erp.utils.PageUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author 柯鑫
 * @ClassName com.hz.erp.service.impl.TemInfoServiceImpl
 * @description 温度信息实现类
 * @create 2020年06月08日 19:06
 */
@Service
public class TemInfoServiceImpl implements TemInfoService {

    private Logger logger = LoggerFactory.getLogger(TemInfoServiceImpl.class);

    @Autowired
    private TemperatureInfoMapper temperatureInfoMapper;

    /**
     * 分页查询所有的温度信息
     * @param temInfoParameterVo
     * @return
     */
    @Override
    public RetResult<PageResult> selectTemInfoAllListByPage(TemInfoParameterVo temInfoParameterVo, HttpServletRequest request) {
        //根据id查询登录者的信息
        String id = request.getSession().getId();
        System.out.println("session........." + id);
        UserVo sessionUser = (UserVo)request.getSession().getAttribute("user");
        if(null == sessionUser){
            return RetResponse.makeErrRsp("请先登录");
        }
        return RetResponse.makeOKRsp(PageUtils.getPageResult(getPageInfo(temInfoParameterVo, sessionUser)));
    }

    /**
     * 分页拆线呢
     * @param temInfoParameterVo
     * @return
     */
    private PageInfo<TemperatureInfoVo> getPageInfo(TemInfoParameterVo temInfoParameterVo, UserVo sessionUser) {

        int pageNum = temInfoParameterVo.getPageNum();
        int pageSize = temInfoParameterVo.getPageSize();
        PageHelper.startPage(pageNum, pageSize);

        List<TemperatureInfoVo> restUserList = new ArrayList<>();
        //ERP查看
        if(RegistrationWayEnum.COME_ERP.getCode().equals(sessionUser.getRegistrationWay())){
            //分级查看        //一级和二级账户和三级查询
            if(ManagementFlagEnum.SUPER_MANAGEMENT.getCode().equals(sessionUser.getManagementFlag())){
                restUserList = temperatureInfoMapper.selectSuperManagementByPage(temInfoParameterVo);

            }else if(ManagementFlagEnum.IS_MANAGEMENT.getCode().equals(sessionUser.getManagementFlag())){
                temInfoParameterVo.setUserId(sessionUser.getId());
                restUserList = temperatureInfoMapper.selectManagementByPage(temInfoParameterVo);
            }else{
                temInfoParameterVo.setUserId(sessionUser.getId());
                restUserList = temperatureInfoMapper.selectNotManagementByPage(temInfoParameterVo);
            }

        }else {
            //前端查看      //个体户查询
            temInfoParameterVo.setUserId(sessionUser.getId());
            restUserList = temperatureInfoMapper.selectNotManagementByPage(temInfoParameterVo);
        }

        //查询出来的数据进行转换
        for (TemperatureInfoVo tmp : restUserList) {
            tmp.setDeleteFlag(DeleteFlagEnum.setCodeGetDesc(tmp.getDeleteFlag()));
            tmp.setTemperatureType(TemperatureEnum.setCodeGetDesc(tmp.getTemperatureType()));
        }

        return new PageInfo<TemperatureInfoVo>(restUserList);
    }


    @Override
    public RetResult<String> insertTmpInfo(TemperatureInfoVo temperatureInfoVo) {

        RetResult<String> validInfo = validInsertTmpInfo(temperatureInfoVo);
        //数据校验
        if(null != validInfo){
            return validInfo;
        }

        //数据转换
        conversionTmpInfo(temperatureInfoVo);

        //插库
        try {
            temperatureInfoMapper.insertTmpInfo(temperatureInfoVo);
            return RetResponse.makeOKRsp("保存温度信息成功");
        } catch (RuntimeException e) {
            logger.error("保存温度信息出错了" + e);
            throw new RuntimeException("保存温度信息出错了", e);
        }
    }

    @Override
    public RetResult<String> insertObtainTokenInfo(JSONObject jsonObject) {

        logger.error("温度数据格式........" + jsonObject);
        System.out.println(jsonObject);

        if(StringUtils.isEmpty(String.valueOf(jsonObject))){
           return RetResponse.makeErrRsp("jsonObject值为null");
        }

        //获取用户子id
        String userId = jsonObject.getString("id");
        //获取token
        String token = jsonObject.getString("token");



        //数据校验
        if(StringUtils.isBlank(userId)){
           return RetResponse.makeErrRsp("id信息为空");
        }
        if(StringUtils.isBlank(token)){
           return RetResponse.makeErrRsp("token信息为空");
        }

        //token 拼接
        List<String> obj = JSONArray.parseArray(token, String.class);

        for (int i = 0; i < obj.size(); i++) {

            
        }


        //唯一标识、设备号
        String temUUidStr = obj.get(0).substring(0, obj.get(0).length() - 28);
        //温度
        String temperatureStr = obj.get(2).substring(obj.get(2).length() - 4);
        //身份证前缀
        String prefix = obj.get(0).substring(obj.get(0).length() - 28);
        //身份证后缀
        String suffix = obj.get(2).substring(0, obj.get(2).length() - 4);


        //转换16进制为温度
        int temCovert = MathUtils.covert(temperatureStr);
        BigDecimal temNum = MathUtils.temConvert(temCovert);

        //身份证
        StringBuffer idCardStr = new StringBuffer();
        idCardStr.append(prefix).append(obj.get(1)).append(suffix);
        //存库
        TemperatureInfoVo temperatureInfoVo = new TemperatureInfoVo();
        temperatureInfoVo.setTemUUID(temUUidStr);
        temperatureInfoVo.setIdCard(String.valueOf(idCardStr));
        temperatureInfoVo.setTemperature(temNum);
        temperatureInfoVo.setUserId(Long.valueOf(userId));

        return insertTmpInfo(temperatureInfoVo);
    }

    /**
     * 获取所有的温度设备信息
     * @return
     */
    @Override
    public RetResult<List<String>> getAllTemUUID(Long childId, HttpServletRequest request) {
        if(childId == null ){
            return RetResponse.makeErrRsp("childId为null,请传入childId");
        }
        UserVo sessionUser = (UserVo)request.getSession().getAttribute("user");
        if(null == sessionUser){
            return RetResponse.makeErrRsp("请先登录");
        }
        List<String> temList = new ArrayList<>();
        //ERP查看
        if(RegistrationWayEnum.COME_ERP.getCode().equals(sessionUser.getRegistrationWay())){
            //分级查看        //一级和二级账户和三级查询  selectSuperManagementTmpUUID/selectManagementTmpUUID/selectNotManagementTmpUUID
            if(ManagementFlagEnum.SUPER_MANAGEMENT.getCode().equals(sessionUser.getManagementFlag())){
                temList = temperatureInfoMapper.selectSuperManagementTmpUUID();
            }else if(ManagementFlagEnum.IS_MANAGEMENT.getCode().equals(sessionUser.getManagementFlag())){
                temList =  temperatureInfoMapper.selectManagementTmpUUID(sessionUser.getId());
            }else{
                temList = temperatureInfoMapper.selectNotManagementTmpUUID(sessionUser.getId());
            }

        }else {
            //前端查看      //个体户查询
            temList = temperatureInfoMapper.selectNotManagementTmpUUID(sessionUser.getId());
        }

        if(CollectionUtils.isEmpty(temList)){
            temList.add("赞无设备");
        }
        return RetResponse.makeOKRsp(temList);
    }


    /**
     * 导出温度信息
     * @param response
     * @param temInfoParameterVo
     * @return
     */
    @Override
    public void exportTmpInfo(HttpServletResponse response, TemInfoParameterVo temInfoParameterVo, HttpServletRequest request) {

        //根据id查询登录者的信息
        UserVo sessionUser = (UserVo)request.getSession().getAttribute("user");
        if(null == sessionUser){
            logger.error("session不存在" + sessionUser);
        }

        List<TemperatureInfoVo> restUserList = new ArrayList<>();
        //ERP查看
        if(RegistrationWayEnum.COME_ERP.getCode().equals(sessionUser.getRegistrationWay())){
            //分级查看        //一级和二级账户和三级查询
            if(ManagementFlagEnum.SUPER_MANAGEMENT.getCode().equals(sessionUser.getManagementFlag())){
                restUserList = temperatureInfoMapper.selectSuperManagementByPage(temInfoParameterVo);

            }else if(ManagementFlagEnum.IS_MANAGEMENT.getCode().equals(sessionUser.getManagementFlag())){
                temInfoParameterVo.setUserId(sessionUser.getId());
                restUserList = temperatureInfoMapper.selectManagementByPage(temInfoParameterVo);
            }else{
                temInfoParameterVo.setUserId(sessionUser.getId());
                restUserList = temperatureInfoMapper.selectNotManagementByPage(temInfoParameterVo);
            }

        }else {
            //前端查看      //个体户查询
            temInfoParameterVo.setUserId(sessionUser.getId());
            restUserList = temperatureInfoMapper.selectNotManagementByPage(temInfoParameterVo);
        }


        if(CollectionUtils.isEmpty(restUserList)){
            logger.error("restUserList集合数据为空");
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("温度信息表");

        String exportName = "TemperatureInfo.xls";

        //设置第一行数据
        String[] headers = { "日期", "公司", "姓名", "设备号", "体温", "状态"};

        //在excel表中添加表头
        HSSFRow row = sheet.createRow(0);

        for(int i = 0; i < headers.length; i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        //在表中存放查询到的数据放入对应的列
        for (int i = 0; i < restUserList.size(); i++) {
            HSSFRow rows = sheet.createRow(rowNum);
            rows.createCell(0).setCellValue(DateUtil.setDateGetStr(restUserList.get(i).getCreateDate()));
            rows.createCell(1).setCellValue("");
            rows.createCell(2).setCellValue("");
            rows.createCell(3).setCellValue(restUserList.get(i).getTemUUID());
            rows.createCell(4).setCellValue(String.valueOf(restUserList.get(i).getTemperature()));
            rows.createCell(5).setCellValue(TemperatureEnum.setCodeGetDesc(restUserList.get(i).getTemperatureType()));
            rowNum ++;
        }
        try{
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=" + exportName);
            response.flushBuffer();
            workbook.write(response.getOutputStream());
        }catch (IOException e){
            throw  new RuntimeException("导出温度信息数据异常");
        }finally {
            try {
                workbook.close();
            } catch (IOException e) {
                throw  new RuntimeException("关闭workbook异常");
            }
        }

    }

    /**
     * 转换数据数据
     * @param temperatureInfoVo
     * @return
     */
    private void conversionTmpInfo(TemperatureInfoVo temperatureInfoVo) {

        //温度类型
        if(MathUtils.compareToBigDecimalGreater(temperatureInfoVo.getTemperature(), new BigDecimal(TemperatureType.TMP_HIGH))){
            temperatureInfoVo.setTemperatureType(TemperatureEnum.high_tmp.getCode());
        }else if(MathUtils.compareToBigDecimalLess(temperatureInfoVo.getTemperature(), new BigDecimal(TemperatureType.TMP_LOW))){
            temperatureInfoVo.setTemperatureType(TemperatureEnum.low_tmp.getCode());
        }else {
            temperatureInfoVo.setTemperatureType(TemperatureEnum.normal_tmp.getCode());
        }

        //是否删除
        temperatureInfoVo.setDeleteFlag(DeleteFlagEnum.NOT_DELETE.getCode());

    }

    private RetResult<String> validInsertTmpInfo(TemperatureInfoVo tmp) {

        if(StringUtils.isBlank(tmp.getTemUUID())){
            return RetResponse.makeErrRsp("温度信息设备号为空!");
        }
        if(StringUtils.isBlank(tmp.getIdCard())){
            return RetResponse.makeErrRsp("身份证信息为空");
        }
        if(MathUtils.compareToDecimalNull(tmp.getTemperature())){
            return RetResponse.makeErrRsp("温度信息为空");
        }
        if(MathUtils.isNullOrZero(tmp.getUserId())){
            return RetResponse.makeErrRsp("关联账户id为空");
        }
        return null;
    }
}
